<?php

/**
 * 发送邮件类
 *
 **/
class Mail {

    /**
     * PHPMailer 对象
     * @var <type>
     */
    private $_mailer = null;

    /**
     * SMTP 配置
     * @var <type>
     */
    private $_smtp = array();

    /**
     * 用户账户配置
     * @var <type>
     */
    private $_auth = array();

    /**
     * 自动加载的 SMTP 配置
     * @var <type>
     */
    private $_autoloadStmp = array(
            '163.com' => array(),
            'qq.com' => array(),
            'gmail.com' => array('host' => 'smtp.gmail.com', 'port' => 465, 'secure' => 'ssl'),
        );

    /**
     * 构造函数
     */
    public function  __construct($domain = '', $config = array()) {

        if ($domain) {
            $this->setSmtp($domain, $config);
        }
    }

    /**
     * 获取 Mailer 对象
     * @return <type>
     */
    private function _getMailer() {

        if (!$this->_mailer) {

            // 新建
            include_once(dirname(__FILE__) . '/Mail/phpmailer/class.phpmailer.php');
            $this->_mailer = new PHPMailer();
            $this->_mailer->PluginDir = dirname(__FILE__) . '/Mail/phpmailer/';
            $this->_mailer->SetLanguage('en', $this->_mailer->PluginDir . 'language/');
            $this->_mailer->IsSMTP();
            $this->_mailer->CharSet = 'UTF-8';
            $this->_mailer->Encoding = 'base64';
        } else {

            // 重置
            $this->_mailer->ClearAllRecipients();
            $this->_mailer->ClearAttachments();
            $this->_mailer->ClearCustomHeaders();
            $this->_mailer->ClearCustomHeaders();
            $this->_mailer->ClearCustomHeaders();
        }
    }

    /**
     * 设置 SMTP 信息
     * @param <type> $domain
     * @param <type> $config
     */
    public function setSmtp($domain, $config = array()) {

        if (!isset($config['host'])) {
            $config['host'] = 'smtp.' . $domain;
        }

        if (!isset($config['port'])) {
            $config['port'] = 25;
        }

        if(!isset($config['secure'])) {
            $config['secure'] = $config['port'] == 465 ? 'ssl' : '';
        }

		if (!isset($config['debug'])) {
			$config['debug'] = false;
		}

        $this->_smtp[$domain] = $config;
    }

    /**
     * 设置帐号信息
	 * 注意：使用 QQ企业邮箱时，username 需要是完整的邮箱（和 email 相同）
	 *
     * @param <type> $domain
     * @param <type> $username
     * @param <type> $password
     * @param <type> $email
     */
    public function setAuth($domain, $username, $password, $email = '') {

        if (!$email) {
            $email = $username . '@' . $domain;
        }

        $this->_auth[$email] = array($username, $password);
    }

    /**
     * 根据发信人设置 发送信息
     */
    public function _loadSmtp() {

        if (!$this->_mailer->From) {
            throw new Mail_Exception('Mail sender not specified!', 1201);
        }

        list($username, $domain) = explode('@', $this->_mailer->From);
        if (!isset($this->_smtp[$domain]) && isset($this->_autoloadStmp[$domain])) {
            $this->setSmtp($domain, $this->_autoloadStmp[$domain]);
        }
        $smtp = $this->_smtp[$domain];
        if (!$smtp) {
            throw new Mail_Exception('No Stmp for domain: ' . $domain);
        }
        $this->_mailer->Host = $smtp['host'];
        $this->_mailer->Port = $smtp['port'];
        $this->_mailer->SMTPSecure = $smtp['secure'];
		if ($smtp['debug']) {
			$this->_mailer->SMTPDebug = 8;// max debug level
		}

        // Auth
        $this->_mailer->SMTPAuth = false;
        if (isset($this->_auth[$this->_mailer->From])) {
            $this->_mailer->SMTPAuth = true;
            $this->_mailer->Username = $this->_auth[$this->_mailer->From][0];
            $this->_mailer->Password = $this->_auth[$this->_mailer->From][1];
        }
    }

    public function send($fromMail, $fromName, $toMail, $toName, $subject, $body, $isHtml = true, $attach = '') {

        // 获取对象
        $this->_getMailer();

        // 发送人
        $this->_mailer->Sender = $fromMail;
        $this->_mailer->From = $fromMail;
        $this->_mailer->FromName = $fromName ? $fromName : current(explode('@', $fromMail));

        // 接收人
        if (!$toMail) {
            throw new Mail_Exception('Mail receiver not specified', 1202);
        }
        if(is_array($toMail)) {
            for($i=0, $L=count($toMail); $i<$L; $i++) {
                $name = isset($toName[$i]) ? $toName[$i] : current(explode('@', $toMail[$i]));
                $this->_mailer->AddAddress($toMail[$i], $name);
            }
        } else {
            $name = isset($toName) ? $toName : current(explode('@', $toMail));
            $this->_mailer->AddAddress($toMail, $name);
        }

        // 加载 stmp 信息
        $this->_loadSmtp();

        // 附件和内容
        $this->_mailer->WordWrap = 50;
        if ($attach) {
            if (is_array($attach)){
                foreach ($attach as $value) {
                    $this->_mailer->AddAttachment($value);
                }
            } else {
                $this->_mailer->AddAttachment($attach);
            }
        }
        $this->_mailer->IsHTML($isHtml);
        $this->_mailer->Subject = $subject;
        $this->_mailer->Body = $body;
        $this->_mailer->AltBody = strip_tags($body);

        // 发送
        try {
            return $this->_mailer->Send() ? true : false;
        } catch (Exception $e) {
            throw new Mail_Exception($e);
        }
    }

	public function getError() {
		return $this->_mailer->ErrorInfo;
	}
}

